// 简单得TCP服务 
let net = require('net')
const PORT = 3000

let server = net.createServer((conn) => {
  console.log('connected')

  conn.on('data' ,(data) => {
    console.log(data + 'form' + conn.remoteAddress + ' ' + conn.remotePort)
    conn.write('Repeating:' + data)
  })

  conn.on('close', () => {
    console.log('client closed connection')
  })
}).listen(PORT)

server.on('listening', () => {
  console.log('listening on ' + PORT)
})

server.on('error', (err) => {

  console.log(err.message)

  if(err.code === 'EADDRINUSE'){
    console.warn('Address in use, retrying....')
    setTimeout(() => {
      server.close();
      server.listen(PORT)
    }, 1000)
  }else{
    console.error(err)
  }
})